<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"><head profile="http://gmpg.org/xfn/11">
<meta name="verify-v1" content="GeXKtanER98tyl4cTdtBqKhayl5odjJIjPACPNxPlNY=">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="icon" type="image/png" href="http://akrabat.com/favicon.png">
<title>Returning JSON from a ZF2 controller action  –   Rob Allen's DevNotes</title>

<link href="Returning%20JSON%20from%20a%20ZF2%20controller%20action%20%E2%80%93%20Rob%20Allen%27s%20DevNotes_files/css.css" rel="stylesheet" type="text/css">

<meta name="readability-verification" content="gVhhHPJN2LhzPExSW85N9vxBRBGz9nmUErVYVLt7">
<meta name="generator" content="WordPress 3.5.1"> <!-- leave this for stats -->

<link href="Returning%20JSON%20from%20a%20ZF2%20controller%20action%20%E2%80%93%20Rob%20Allen%27s%20DevNotes_files/css.css" rel="stylesheet" type="text/css">
<link rel="stylesheet" href="Returning%20JSON%20from%20a%20ZF2%20controller%20action%20%E2%80%93%20Rob%20Allen%27s%20DevNotes_files/style.css" type="text/css" media="screen">
<link rel="alternate" type="application/rss+xml" title="Rob Allen's DevNotes RSS Feed" href="http://akrabat.com/feed/">

<style type="text/css" media="screen">


</style>

<style type="text/css">/**
 * GeSHi Dynamically Generated Stylesheet
 * --------------------------------------
 * Dynamically generated stylesheet for php
 * CSS class: , CSS id: 
 * GeSHi (C) 2004 - 2007 Nigel McNie, 2007 - 2008 Benny Baumann
 * (http://qbnz.com/highlighter/ and http://geshi.org/)
 * --------------------------------------
 */
.php .de1, .php .de2 {font: normal normal 1em/1.2em monospace; margin:0; padding:0; background:none; vertical-align:top;}
.php  {font-family:monospace;}
.php .imp {font-weight: bold; color: red;}
.php li, .php .li1 {font-weight: normal; vertical-align:top;}
.php .ln {width:1px;text-align:right;margin:0;padding:0 2px;vertical-align:top;}
.php .li2 {font-weight: bold; vertical-align:top;}
.php .kw1 {color: #b1b100;}
.php .kw2 {color: #000000; font-weight: bold;}
.php .kw3 {color: #990000;}
.php .kw4 {color: #009900; font-weight: bold;}
.php .co1 {color: #666666; font-style: italic;}
.php .co2 {color: #666666; font-style: italic;}
.php .co3 {color: #0000cc; font-style: italic;}
.php .co4 {color: #009933; font-style: italic;}
.php .coMULTI {color: #666666; font-style: italic;}
.php .es0 {color: #000099; font-weight: bold;}
.php .es1 {color: #000099; font-weight: bold;}
.php .es2 {color: #660099; font-weight: bold;}
.php .es3 {color: #660099; font-weight: bold;}
.php .es4 {color: #006699; font-weight: bold;}
.php .es5 {color: #006699; font-weight: bold; font-style: italic;}
.php .es6 {color: #009933; font-weight: bold;}
.php .es_h {color: #000099; font-weight: bold;}
.php .br0 {color: #009900;}
.php .sy0 {color: #339933;}
.php .sy1 {color: #000000; font-weight: bold;}
.php .st0 {color: #0000ff;}
.php .st_h {color: #0000ff;}
.php .nu0 {color: #cc66cc;}
.php .nu8 {color: #208080;}
.php .nu12 {color: #208080;}
.php .nu19 {color:#800080;}
.php .me1 {color: #004000;}
.php .me2 {color: #004000;}
.php .re0 {color: #000088;}
.php .ln-xtra, .php li.ln-xtra, .php div.ln-xtra {background-color: #ffc;}
.php span.xtra { display:block; }
</style><link rel="stylesheet" id="wp_geshi_wp-geshi-highlight-css" href="Returning%20JSON%20from%20a%20ZF2%20controller%20action%20%E2%80%93%20Rob%20Allen%27s%20DevNotes_files/wp-geshi-highlight.css" type="text/css" media="all">
<link rel="EditURI" type="application/rsd+xml" title="RSD" href="http://akrabat.com/xmlrpc.php?rsd">
<link rel="wlwmanifest" type="application/wlwmanifest+xml" href="http://akrabat.com/wp-includes/wlwmanifest.xml"> 
<link rel="prev" title="Automatic Apache vhosts" href="http://akrabat.com/computing/automatic-apache-vhosts/">
<link rel="next" title="Returning JSON using the Accept header in ZF2" href="http://akrabat.com/zend-framework-2/returning-json-using-the-accept-header-in-zf2/">
<meta name="generator" content="WordPress 3.5.1">
<link rel="canonical" href="http://akrabat.com/zend-framework-2/returning-json-from-a-zf2-controller-action/">
<link rel="shortlink" href="http://akrabat.com/2174">
<link rel="payment" type="text/html" title="Flattr this!" href="https://flattr.com/submit/auto?user_id=akrabat&amp;popout=1&amp;url=http%3A%2F%2Fakrabat.com%2Fzend-framework-2%2Freturning-json-from-a-zf2-controller-action%2F&amp;language=en_GB&amp;category=text&amp;title=Returning+JSON+from+a+ZF2+controller+action&amp;description=Developing+PHP+software+in+the+Real+World%2C+by+Rob+Allen&amp;tags=blog">

<link rel="openid.server" href="http://www.myopenid.com/server">
<link rel="openid.delegate" href="http://akrabat.myopenid.com/">

</head>
<body data-twttr-rendered="true">
<div id="page">


<div id="header">
	<div id="headerimg">
		<h1><a href="http://akrabat.com/">Rob Allen's DevNotes</a></h1>
		<div class="description">Developing PHP software in the Real World, by Rob Allen</div>
	</div>
	<ul class="topnav">
		<li><a href="http://akrabat.com/">Home</a></li>
		<li><a href="http://akrabat.com/zend-framework-2-tutorial/">ZF2 tutorial</a></li>
		<li><a href="http://akrabat.com/zend-framework-tutorial/">ZF1 tutorial</a></li>
		<li><a href="http://akrabat.com/talks/">Talks</a></li>
		<li><a href="http://akrabat.com/archives/">Archives</a></li>
		<li><a href="http://akrabat.com/about/">About</a></li>
	</ul>
</div>
<div id="container">
	<div id="content" class="column">
    <div id="pad">

  		<div class="navigation">
			<div class="alignleft">« <a href="http://akrabat.com/computing/automatic-apache-vhosts/" rel="prev">Automatic Apache vhosts</a></div>
			<div class="alignright"><a href="http://akrabat.com/zend-framework-2/returning-json-using-the-accept-header-in-zf2/" rel="next">Returning JSON using the Accept header in ZF2</a> »</div>
		</div>

		<div class="post " id="post-2174">
			<h2><a href="http://akrabat.com/zend-framework-2/returning-json-from-a-zf2-controller-action/" rel="bookmark" title="Permanent Link: Returning JSON from a ZF2 controller action">Returning JSON from a ZF2 controller action</a></h2>

			<div class="entry">
				<p>The new view layer in Zend Framework 2 can be set up to return 
JSON rather than rendered HTML relatively easily. There are two steps to
 this:</p>
<h3>Set up the JsonStrategy</h3>
<p>Firstly we need to set up the view's <tt>JsonStrategy</tt> to check to a situation when returning JSON is required and then to render out JSON for us. The <tt>JsonStrategy</tt> will cause the <tt>JsonRenderer</tt> to be run in two situations:</p>
<ol>
<li>The view model returned by the controller action is a <tt>JsonModel</tt></li>
<li>The HTTP Accept header sent in the Request include "application/json"</li>
</ol>
<p>To enable the <tt>JsonStrategy</tt>, we simply configure it in the module's config.php file:</p>
<p><strong>module/Application/config/module.config.php:</strong></p>
<pre>    'view_manager' =&gt; array(
        'display_not_found_reason' =&gt; true,
        'display_exceptions'       =&gt; true,
        'doctype'                  =&gt; 'HTML5',
        'not_found_template'       =&gt; 'error/404',
        'exception_template'       =&gt; 'error/index',
        'template_map' =&gt; array(
            'layout/layout' =&gt; __DIR__ . '/../view/layout/layout.phtml',
            'index/index'   =&gt; __DIR__ . '/../view/index/index.phtml',
            'error/404'     =&gt; __DIR__ . '/../view/error/404.phtml',
            'error/index'   =&gt; __DIR__ . '/../view/error/index.phtml',
        ),
        'template_path_stack' =&gt; array(
            'application' =&gt; __DIR__ . '/../view',
        ),
<strong>        'strategies' =&gt; array(
            'ViewJsonStrategy',
        ),
</strong>    ),
</pre>
<p>As you can see, in the <tt>view_manager()</tt> add <tt>ViewJsonStrategy</tt> to the <tt>strategies</tt> array.</p>
<h3>Return a JsonModel from the controller action</h3>
<p>To send JSON to the client when the Accept header isn't application/json, we use a <tt>JsonModel</tt> in a controller action like this:</p>
<p><strong>module/Application/src/Application/Controller/IndexController.php:</strong></p>


<div class="wp-geshi-highlight-wrap5"><div class="wp-geshi-highlight-wrap4"><div class="wp-geshi-highlight-wrap3"><div class="wp-geshi-highlight-wrap2"><div class="wp-geshi-highlight-wrap"><div class="wp-geshi-highlight"><div class="php"><pre class="de1"><span class="kw2">namespace</span> Application\Controller<span class="sy0">;</span>
&nbsp;
<span class="kw2">use</span> Zend\Mvc\Controller\ActionController<span class="sy0">;</span>
<span class="kw2">use</span> Zend\View\Model\ViewModel<span class="sy0">;</span>
<span class="kw2">use</span> Zend\View\Model\JsonModel<span class="sy0">;</span>
&nbsp;
<span class="kw2">class</span> IndexController <span class="kw2">extends</span> ActionController
<span class="br0">{</span>
    <span class="kw2">public</span> <span class="kw2">function</span> indexAction<span class="br0">(</span><span class="br0">)</span>
    <span class="br0">{</span>
        <span class="re0">$result</span> <span class="sy0">=</span> <span class="kw2">new</span> JsonModel<span class="br0">(</span><span class="kw3">array</span><span class="br0">(</span>
	    <span class="st_h">'some_parameter'</span> <span class="sy0">=&gt;</span> <span class="st_h">'some value'</span><span class="sy0">,</span>
            <span class="st_h">'success'</span><span class="sy0">=&gt;</span><span class="kw4">true</span><span class="sy0">,</span>
        <span class="br0">)</span><span class="br0">)</span><span class="sy0">;</span>
&nbsp;
        <span class="kw1">return</span> <span class="re0">$result</span><span class="sy0">;</span>
    <span class="br0">}</span>
<span class="br0">}</span></pre></div></div></div></div></div></div></div>


<p>The output will now be JSON. Obviously, if you're sending JSON back 
based on the Accept header, then you can return a normal ViewModel.</p>
<p><em>Note that this entry was updated on 20 June 2012 to reflect updates to ZF2.</em></p>
<p>See also: <a href="http://akrabat.com/zend-framework-2/returning-json-using-the-accept-header-in-zf2/">Returning JSON using the Accept header in ZF2</a></p>

				
                <div class="social">
                    <span>Like this article? </span>
                    <ul>
                        <li><a href="http://akrabat.com/?flattrss_redirect&amp;id=2174&amp;md5=d823f68ea36186881822028c47cfcf22" title="Flattr" target="_blank"><img src="Returning%20JSON%20from%20a%20ZF2%20controller%20action%20%E2%80%93%20Rob%20Allen%27s%20DevNotes_files/flattr-badge-large.png" alt="flattr this!"></a></li>
                        <li><iframe data-twttr-rendered="true" title="Twitter Tweet Button" style="width: 55px; height: 20px;" class="twitter-share-button twitter-count-none" src="Returning%20JSON%20from%20a%20ZF2%20controller%20action%20%E2%80%93%20Rob%20Allen%27s%20DevNotes_files/tweet_button.html" allowtransparency="true" frameborder="0" scrolling="no"></iframe><script src="Returning%20JSON%20from%20a%20ZF2%20controller%20action%20%E2%80%93%20Rob%20Allen%27s%20DevNotes_files/ga.js" async="" type="text/javascript"></script><script type="text/javascript" src="Returning%20JSON%20from%20a%20ZF2%20controller%20action%20%E2%80%93%20Rob%20Allen%27s%20DevNotes_files/widgets.js"></script></li>

                    </ul>
                </div>

				<p class="postmetadata alt">
					<small>
						This entry was posted
												on Thursday, 29th March 2012 at 09:55						and is filed under <a href="http://akrabat.com/category/zend-framework-2/" title="View all posts in Zend Framework 2" rel="category tag">Zend Framework 2</a>.
												
					</small>
				</p>

			</div>
		</div>

	
<!-- You can start editing here. -->


  		<!-- If comments are closed. -->
			    	    
	


	
	</div>
	</div>
	<div id="sidebar" class="column">
		<ul>

			<li>
				<form method="get" id="searchform" action="http://akrabat.com/">
<div><input name="s" id="s" type="text">
<input id="searchsubmit" value="Search" type="submit">
</div>
</form>
			</li>
                        <li style="margin-top: 10px;">
                           <a href="http://itunes.apple.com/app/daily-jotter/id411293034?mt=12" title="">
 <img src="Returning%20JSON%20from%20a%20ZF2%20controller%20action%20%E2%80%93%20Rob%20Allen%27s%20DevNotes_files/dj-banner-150.jpg" alt="Daily Jotter on iTunes" border="0" height="225" width="150"></a>
                        </li>
                        <li style="margin-top: 10px;">
                           <p style="margin-bottom: 3px;">My <a href="http://www.zendframeworkinaction.com/">Zend Framework Book</a>:</p>
                           <a href="http://www.zendframeworkinaction.com/" title="">
 <img src="Returning%20JSON%20from%20a%20ZF2%20controller%20action%20%E2%80%93%20Rob%20Allen%27s%20DevNotes_files/allen_cover150.jpg" alt="Zend Framework in Action cover" border="0" height="188" width="150"></a>
                        </li>
			<li><h2>Rob Allen</h2>
			<p>
Rob is a PHP and Zend Framework expert based in Worcester, UK. He is the Technical Director for <a href="http://www.bigroominternet.co.uk/">Big Room Internet</a> and the author of <a href="http://www.zendframeworkinaction.com/">Zend Framework in Action</a>.</p>
<p>He also supports the <a href="http://www.cahp.girl-wonder.org/">Con Anti-Harrassment Project</a>.</p>
<p>Around the web:<br>
Twitter: <a href="http://www.twitter.com/akrabat">@akrabat</a><br>
Flickr: <a href="http://www.flickr.com/photos/akrabat">photos</a><br>
Linked in: <a href="http://uk.linkedin.com/in/akrabat">profile</a><br>
</p>

			</li>

                        <li style="margin-top: 10px;">
                           
                           <a href="http://www.zend.com/en/services/certification/framework/education-advisory-board-zf" title="">
 <img src="Returning%20JSON%20from%20a%20ZF2%20controller%20action%20%E2%80%93%20Rob%20Allen%27s%20DevNotes_files/ZF-Education-Advisory-Board-S.png" alt="Zend Framework Education Advisory Board Member" border="0" height="35" width="155"></a>
                        </li>

			<li class="pagenav"><h2>Other pages</h2><ul><li class="page_item page-item-95"><a href="http://akrabat.com/akras-diary/">Akra's Diary</a></li>
<li class="page_item page-item-1739"><a href="http://akrabat.com/disclosure-policy/">Disclosure policy</a></li>
<li class="page_item page-item-18"><a href="http://akrabat.com/dynamic-javascript-tabs/">Dynamic JavaScript Tabs</a></li>
<li class="page_item page-item-2066"><a href="http://akrabat.com/license-for-code-published-on-this-site/">License for code on this site</a></li>
<li class="page_item page-item-459"><a href="http://akrabat.com/shorter-links/">Shorter Links WP plugin</a></li>
</ul></li>


			
		</ul>
	</div>
</div>
<div id="footer-wrapper">
<div id="footer">
	<p style="float: right">Copyright © 2005-2013 Rob Allen. All rights reserved.</p>
	<p>
		<a href="http://akrabat.com/disclosure-policy/">Disclosure policy</a>
		| <a href="http://akrabat.com/license-for-code-published-on-this-site/">License for code on this site</a>
		| <a href="feed:http://akrabat.com/feed/">Entries RSS</a>
		| <a href="feed:http://akrabat.com/comments/feed/">Comments</a>
		<!-- 26 queries. 0.313 seconds. -->
		
	</p>
</div>
</div>
</div>


<script type="text/javascript">
  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-365662-1']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();
</script>







</body></html>
<!-- Dynamic page generated in 0.303 seconds. -->
<!-- Cached page generated by WP-Super-Cache on 2013-05-03 15:32:47 -->
<!-- super cache -->